﻿/******************************************************************
** 文 件 名: BD_Contract_Edit.aspx.cs
** Copyright (c) 2010-2012 Honestysoft (GuangZhou) Co.,LTD
** 创 建 人: 此代码由生成器自动生成
** 创建日期: 2012-3-8 2:35:58
** 描    述: 基础资料-合同信息编辑页面
** 版    本: 2.0.0.0
** 修改描述:
** 修 改 人:
** 修改日期:
******************************************************************/
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Honestysoft.BaseLibrary;
using Honestysoft.BaseObject;
using Honestysoft.BaseLibrary.ExceptionHandling;
using Honestysoft.Baseframework.WebUI;
using Honestysoft.Financing.Model;
using System.Data.Common;
using System.Collections.Generic;
using Honestysoft.Baseframework.Model;


namespace Honestysoft.Financing.WebUI.Module.Contract
{
    public partial class ContractEdit_ToDatabase : BasePage
	{	
		protected override void Page_Load(object sender, EventArgs e)
        {
			base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                //Utils.ContractSession.Clear();
				BindControl();
                Bind();
                BindContractChanges();
                BindAT();
                BindDOwner();
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //string json = hidAddChange.Value;
            //hidAddChange.Value = "";
            //BD_ContractChange newItem = JsonHelper.JsonDeserialize<BD_ContractChange>(json);
            //newItem.SponsorName = Server.UrlDecode(newItem.SponsorName);
            //newItem.Remark = Server.UrlDecode(newItem.Remark);
            //if (obj.ContractChanges == null) { obj.ContractChanges = new List<BD_ContractChange>(); }
            //obj.ContractChanges.Insert(0, newItem);
            //BindContractChanges();
            //Page.ClientScript.RegisterStartupScript(typeof(string), "doTab", "document.getElementById('li1').click();", true);
           
        }

        private BD_Contract obj
        {
            get
            {
                object obj = ViewState["theContract"];
                return obj == null ? null : obj as BD_Contract;
            }
            set
            {
                ViewState["theContract"] = value;
            }
        }
		
		private void BindControl()
		{
			ControlHelper.BindDictionary(ddlContractCategory, "ContractCategory");
            //if (Request.QueryString["IsToDatabase"] == "1" ||
            //    string.IsNullOrEmpty(Request.QueryString["ID"]))
            //{
            //    btnAdd.Enabled = false;
            //}
            //if (Request.QueryString["IsToDatabase"] != "1" &&
            //    !string.IsNullOrEmpty(Request.QueryString["ID"]))
            //{
            //    btnAdd.Attributes.Add("onclick", "javascript:openDialog('" + Globals.Home + "/Contract/BD_ContractChange_Edit.aspx?FunctionID=" + FunctionID + "&ContractID=" + Request.QueryString["ID"] + "'," + ModalDialogSize.EditWidth + ", " + ModalDialogSize.EditHeight + ", '新增合同变更情况');return false;");
            //}
                //numTotalPrice.Attributes.Add("onpropertychange", "javascript:document.getElementById('" + hidChangePrice.ClientID + "').value=this.value;document.getElementById('" + numChangePrice.ClientID + "').value=this.value;"); 
		}

        private void Bind()
        {
            if (Request.QueryString["IsToDatabase"] == "1")//属于从收文回执里面进行合同入库的
            {
                txtName.Attributes.Add("onchange", "javascript:getLikeContractByName(this.value);");
                numTotalPrice.Attributes.Add("onchange", "javascript:getLikeContractByPrice(this.value);");

                Bu_DocReceive_Temp docRec = new BaseBusinessLogic<Bu_DocReceive_Temp>(Globals.CurrentConnStringName).GetEntity(Request.QueryString["ID"]);
                obj = new BD_Contract();
                obj.ProjectName = docRec.ProjectName;
                obj.ProjectID = docRec.ProjectID;
                obj.Code = docRec.ContractCode;
                obj.Name = docRec.ContractName;
                obj.ContractorName = docRec.ContractorName;
                //查找该单位，如果没有，则赋值为名称，保存时自动新增
                QueryParameters query = new QueryParameters();
                query.Add("CompName", docRec.ContractorName, QueryParameters.OperatorType.Equal);
                List<Org_Company> lsComp = new BaseBusinessLogic<Org_Company>(Globals.CurrentConnStringName).GetEntitys(query);
                if (lsComp != null && lsComp.Count == 1)
                {
                    obj.Contractor = lsComp[0].ID;
                }
                else
                {
                    obj.Contractor = docRec.ContractorName;
                }
                if (ddlContractCategory.Items != null && ddlContractCategory.Items.Count > 0)
                {
                    ddlContractCategory.SelectedIndex = 0;
                    obj.ContractCategory = ddlContractCategory.SelectedValue;
                }
                obj.dataState = Model.EnumItem.DataState.New;
                obj.CreateTime = DateTime.Now;
                obj.Creator = UserLoginer.LoginUser.ID;
                obj.IsInit = true;
                obj.ConfirmOpinion = "";
                obj.ConfirmTime = DateTime.Now;
                obj.ConfirmUser = UserLoginer.LoginUser.ID;
                //numTotalPrice.Attributes.Add("onpropertychange", "javascript:document.getElementById('" + hidChangePrice.ClientID + "').value=this.value;document.getElementById('" + numChangePrice.ClientID + "').value=this.value;");
            }
            else
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))//修改
                {
                    obj = new Honestysoft.Financing.BusinessLogic.Contract(Globals.CurrentConnStringName).GetContract(Request.QueryString["ID"]);
                    obj.dataState = Model.EnumItem.DataState.Modify;
                    //if (!obj.HasChangeRecord)
                    //{
                    //    numTotalPrice.Attributes.Add("onpropertychange", "javascript:document.getElementById('" + hidChangePrice.ClientID + "').value=this.value;document.getElementById('" + numChangePrice.ClientID + "').value=this.value;");
                    //}
                    //btnAdd.Attributes.Add("onclick", "javascript:return AddChange();");
                }
                else //新增
                {
                    obj = new BD_Contract();
                    obj.dataState = Model.EnumItem.DataState.New;
                    obj.ProjectID = Request.QueryString["ProjectID"];
                    obj.Code = new Honestysoft.Financing.BusinessLogic.Contract(Globals.CurrentConnStringName).GetNextContractCode(Request.QueryString["ProjectID"]);
                    obj.ProjectName = new Honestysoft.Financing.BusinessLogic.Project(Globals.CurrentConnStringName).GetProjectName(Request.QueryString["ProjectID"]);
                    obj.CreateTime = DateTime.Now;
                    obj.Creator = UserLoginer.LoginUser.ID;
                    obj.IsInit = false;
                    if (Request.QueryString["ContractCategory"] == "0")
                    {
                        if (ddlContractCategory.Items != null && ddlContractCategory.Items.Count > 0)
                        {
                            ddlContractCategory.SelectedIndex = 0;
                            obj.ContractCategory = ddlContractCategory.SelectedValue;
                        }
                    }
                    else
                    {
                        obj.ContractCategory = Request.QueryString["ContractCategory"];
                        ddlContractCategory.SelectedValue = Request.QueryString["ContractCategory"];
                    }
                    //numTotalPrice.Attributes.Add("onpropertychange", "javascript:document.getElementById('" + hidChangePrice.ClientID + "').value=this.value;document.getElementById('" + numChangePrice.ClientID + "').value=this.value;");
                }
            }
            txtProject.Text = obj.ProjectName;
            //txtProject.Enabled = false;
            ddlContractCategory.SelectedValue = obj.ContractCategory;
            lblFCode.Text = obj.Code.Substring(0, obj.Code.IndexOf("C") + 1);
            txtCode.Text = obj.Code.Substring(obj.Code.Length - 3);
            txtName.Text = obj.Name;
            dtpSignDate.Text = (obj.SignDate.HasValue ? obj.SignDate.Value.ToString("yyyy-MM-dd") : "");
            numTotalPrice.Text = obj.TotalPrice.ToString("0.00");
            //numChangePrice.Text = obj.CurChangePrice.ToString("0.00");
            //hidChangePrice.Value = numChangePrice.Text;
            //numReserveAmount.Text = (obj.ReserveAmount.HasValue ? obj.ReserveAmount.Value.ToString("0.00") : "");
            FCKeditor2.Value = obj.PaymentCondition;
            hidContractor.Value = obj.Contractor;
            txtContractor.Text = obj.ContractorName;
            txtBankAccount.Text = obj.BankAccount;
            txtBankName.Text = obj.BankName;
            txtRemark.Text = obj.Remark;
            hidDBankCompany.Value = obj.DBankCompanyID;
            txtDBankCompany.Text = obj.DBankCompanyName;
            if (obj.IsInit)
            {
                //txtCode.Enabled = false;
                //txtName.Enabled = false;
                txtProject.Enabled = false;
                //numTotalPrice.Enabled = false;
                //btnSelect2.Enabled = false;
            }
        }

        private void BindAT()
        {
            if (Request.QueryString["IsToDatabase"] != "1" && !string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                QueryParameters query = new QueryParameters();
                query.Add("ContractID", Request.QueryString["ID"], QueryParameters.OperatorType.Equal);
                OrderParameters order = new OrderParameters();
                order.Add("Code");
                DataTable dt = new BaseBusinessLogic<Bu_AuditTable>(Globals.CurrentConnStringName).GetTable(query, order);
                repATList.DataSource = dt;
                repATList.DataBind();
                decimal amount_S = 0, giveAmount = 0, bfAmount = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    amount_S += Convert.ToDecimal(dr["Amount_S"]);
                    giveAmount += Convert.ToDecimal(dr["GiveAmount"]);
                    bfAmount += Convert.ToDecimal(dr["BFAmount"]);
                }
                lblAmount_S.Text = string.Format("{0:N}", amount_S);
                lblGiveAmount.Text = string.Format("{0:N}", giveAmount);
                lblBFAmount.Text = string.Format("{0:N}", bfAmount);
                lblPP_Amount_S.Text = (obj.TotalPrice == 0 ? "" : string.Format("{0:P}", amount_S / obj.TotalPrice));
                lblPP_GiveAmount.Text = (obj.TotalPrice == 0 ? "" : string.Format("{0:P}", giveAmount / obj.TotalPrice));
                lblPP_BFAmount.Text = (obj.TotalPrice == 0 ? "" : string.Format("{0:P}", bfAmount / obj.TotalPrice));
            }
        }

        protected string GetIsChecked(object isChecked)
        {
            if (!Convert.ToBoolean(isChecked)) { return ""; }
            return "checked='checked'";
        }

        private void BindDOwner()
        {
            if (Request.QueryString["IsToDatabase"] == "1")
            {
                return;
            }
            QueryParameters query = new QueryParameters();
            OrderParameters order = new OrderParameters();
            query.Add("ProjectID", obj.ProjectID, QueryParameters.OperatorType.Equal);
            query.Add("UnitType", ((int)Honestysoft.Financing.Model.EnumItem.UnitType.DOwner).ToString(), QueryParameters.OperatorType.Equal);
            order.Add("SortCode");
            DataTable dt = new BaseBusinessLogic<BD_ProjectCompany>(Globals.CurrentConnStringName).GetTable(query,order);
            dt.Columns.Add("IsChecked", typeof(bool));
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))//修改
            {
                query = new QueryParameters();
                query.Add("ContractID",Request.QueryString["ID"], QueryParameters.OperatorType.Equal);
                DataView dvContractDOwner = new BaseBusinessLogic<BD_Contract_ProjectDOwner>(Globals.CurrentConnStringName).GetTable(query).DefaultView;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["IsChecked"] = false;
                    dvContractDOwner.RowFilter = "CompanyID='"+dr["CompanyID"].ToString()+"'";
                    if (dvContractDOwner.Count == 1)
                    {
                        dr["IsChecked"] = true;
                    }
                }
            }
            else //新增
            {
                foreach (DataRow dr in dt.Rows)
                {
                    dr["IsChecked"] = false;
                }
            }
            rptDOwnerList.DataSource = dt;
            rptDOwnerList.DataBind();
        }

        /// <summary>
        /// 绑定列表
        /// </summary>
        private void BindContractChanges()
        {
            rptList.DataSource = obj.ContractChanges;
            rptList.DataBind();
            //hidCurPrice.Value = obj.CurChangePrice.ToString("0.00");
            //hidLastDate.Value = obj.LastChangeDate.ToString("yyyy-MM-dd");
            //Page.ClientScript.RegisterStartupScript(typeof(string), "bindChangePrice", "window.parent.setChangePrice('" + obj.CurChangePrice.ToString("0.00") + "');", true);
        }

        protected string GetCheckbox(string dataId)
        {
            return "";
        }
        protected string GetButtonScript(string dataId)
        {
            string url = "";
            url += "<a href=\"#\" onclick=\"javascript:setDefaultBank('" + dataId + "');\">设为默认</a>";
            //if (hidIsInit.Value != "1")//已初始化
            //{
            //    url += "&nbsp;&nbsp;<a href=\"#\" onclick=\"javascript:addDeleteBank('" + dataId + "');\">删除</a>";
            //}
            return url;
        }

		protected void btnOK_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["IsToDatabase"] == "1")
            {
                ToDatabase();
            }
            else
            {
                DbTransaction transaction = Honestysoft.BaseLibrary.Data.DatabaseProvider.GetDbTransaction(Globals.CurrentConnStringName);
                DbConnection connection = transaction.Connection;
                try
                {
                    SetSubmitObject();
                    string maxCode = "";
                     Honestysoft.Financing.BusinessLogic.Reports rptBll = new BusinessLogic.Reports(Globals.CurrentConnStringName);
            
                    if (txtDBankCompany.Text.Trim().Length > 0)//需要新增单位
                    {
                        string id = rptBll.GetCompanyIdByName(txtDBankCompany.Text.Trim(),transaction);
                        if (id == "")
                        {
                            Org_Company newCompany = new Org_Company();
                            newCompany.CategoryID = ConfigurationManager.AppSettings["CompanyCategory_SG"];
                            if (maxCode == "")
                            {
                                maxCode = new Honestysoft.Financing.BusinessLogic.Reports(Globals.CurrentConnStringName).GetMaxCompanyCode();
                            }
                            newCompany.CompCode = "GS-" + (Convert.ToInt32(maxCode.Substring(3)) + 1).ToString().PadLeft(4, '0');
                            maxCode = newCompany.CompCode;
                            newCompany.CompName = txtDBankCompany.Text;
                            newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                            newCompany.IsInner = false;
                            newCompany.IsValid = true;
                            newCompany.SortCode = Convert.ToInt32(maxCode.Substring(3)) + 1;
                            obj.DBankCompanyID = newCompany.ID;
                            new BaseBusinessLogic<Org_Company>(Globals.CurrentConnStringName).CreateEntity(newCompany, transaction);
                        }
                        else
                        {
                            obj.DBankCompanyID = id;
                        }
                    }
                    new Honestysoft.Financing.BusinessLogic.Contract(Globals.CurrentConnStringName).SaveContract(obj,Request["chkID"] + "", transaction);
                    transaction.Commit();
                    ScriptHelper.Window.AlertClose("保存成功！", true);
                }
                catch (BaseException bex)
                {
                    transaction.Rollback();
                    ExceptionHelper.ExceptionDistribute(bex, false);
                    ScriptHelper.Window.Alert(bex.Message);
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    ExceptionHelper.ExceptionDistribute(ex, false);
                    ScriptHelper.Window.Alert("保存失败！系统发生了未知错误！");
                }
                finally
                {
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void ToDatabase()
        {
            DbTransaction transaction = Honestysoft.BaseLibrary.Data.DatabaseProvider.GetDbTransaction(Globals.CurrentConnStringName);
            DbConnection connection = transaction.Connection;
            try
            {
                SetSubmitObject();
                string maxCode = "";
                Honestysoft.Financing.BusinessLogic.Reports rptBll = new BusinessLogic.Reports(Globals.CurrentConnStringName);
            
                if (hidContractor.Value == txtContractor.Text)//需要新增单位
                {
                    Org_Company newCompany = new Org_Company();
                    newCompany.CategoryID = ConfigurationManager.AppSettings["CompanyCategory_SG"];
                    maxCode = rptBll.GetMaxCompanyCode();
                    newCompany.CompCode = "GS-" + (Convert.ToInt32(maxCode.Substring(3)) + 1).ToString().PadLeft(4, '0');
                    maxCode = newCompany.CompCode;
                    newCompany.CompName = txtContractor.Text;
                    newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                    newCompany.IsInner = false;
                    newCompany.IsValid = true;
                    newCompany.SortCode = Convert.ToInt32(maxCode.Substring(3)) + 1;
                    obj.Contractor = newCompany.ID;
                    new BaseBusinessLogic<Org_Company>(Globals.CurrentConnStringName).CreateEntity(newCompany, transaction);
                }
                if (txtDBankCompany.Text.Trim().Length > 0)//需要新增单位
                {
                    string id = rptBll.GetCompanyIdByName(txtDBankCompany.Text.Trim(), transaction);
                    if (id == "")
                    {
                        Org_Company newCompany = new Org_Company();
                        newCompany.CategoryID = ConfigurationManager.AppSettings["CompanyCategory_SG"];
                        if (maxCode == "")
                        {
                            maxCode = new Honestysoft.Financing.BusinessLogic.Reports(Globals.CurrentConnStringName).GetMaxCompanyCode();
                        }
                        newCompany.CompCode = "GS-" + (Convert.ToInt32(maxCode.Substring(3)) + 1).ToString().PadLeft(4, '0');
                        maxCode = newCompany.CompCode;
                        newCompany.CompName = txtDBankCompany.Text;
                        newCompany.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        newCompany.IsInner = false;
                        newCompany.IsValid = true;
                        newCompany.SortCode = Convert.ToInt32(maxCode.Substring(3)) + 1;
                        obj.DBankCompanyID = newCompany.ID;
                        new BaseBusinessLogic<Org_Company>(Globals.CurrentConnStringName).CreateEntity(newCompany, transaction);
                    }
                    else
                    {
                        obj.DBankCompanyID = id;
                    }
                }
                new Honestysoft.Financing.BusinessLogic.Contract(Globals.CurrentConnStringName).ContractToDatabase(obj, Request.QueryString["ID"], ConfigurationManager.AppSettings["YZID"], Request["chkID"] + "", transaction);
                transaction.Commit();
                ScriptHelper.Window.AlertClose("合同入库成功！", true);
            }
            catch (BaseException bex)
            {
                transaction.Rollback();
                ExceptionHelper.ExceptionDistribute(bex, false);
                ScriptHelper.Window.Alert(bex.Message);
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                ExceptionHelper.ExceptionDistribute(ex, false);
                ScriptHelper.Window.Alert("合同入库失败！系统发生了未知错误！");
            }
            finally
            {
                connection.Close();
            }
        }
		/// <summary>
        /// 得到提交对象
        /// </summary>
        /// <returns></returns>
        private void SetSubmitObject()
        {
            if (Request.QueryString["IsToDatabase"] == "1" || string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                obj.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                //obj.ChangePrice = Convert.ToDecimal(hidChangePrice.Value);
            }
            else
            {
                decimal totalPrice = 0;
                if (numTotalPrice.Text.Trim().Length > 0) { totalPrice = Convert.ToDecimal(numTotalPrice.Text); }
                if (obj.TotalPrice != totalPrice)
                {
                    if (obj.ContractChanges == null)
                    {
                        obj.ContractChanges = new List<BD_ContractChange>();
                    }
                    BD_ContractChange changeItem = new BD_ContractChange();
                    changeItem.ChangeDate = DateTime.Now;
                    changeItem.ChangeMoney = totalPrice;
                    changeItem.ContractID = obj.ID;
                    changeItem.CreateTime = DateTime.Now;
                    changeItem.dataState = Model.EnumItem.DataState.New;
                    changeItem.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                    changeItem.IsConfirm = true;
                    changeItem.Remark = "";
                    changeItem.SourceMoney = obj.TotalPrice;
                    changeItem.Sponsor = UserLoginer.LoginUser.ID;
                    changeItem.SponsorName = UserLoginer.LoginUser.Name;
                    obj.ContractChanges.Add(changeItem);
                }
            }
            obj.ContractCategory = ddlContractCategory.SelectedValue;
            obj.Code = lblFCode.Text + txtCode.Text;
            obj.Name = txtName.Text;
            if (dtpSignDate.Text.Trim().Length > 0) { obj.SignDate = Convert.ToDateTime(dtpSignDate.Text); }
            if (numTotalPrice.Text.Trim().Length > 0) { obj.TotalPrice = Convert.ToDecimal(numTotalPrice.Text); }

            obj.Stage = 0;
            obj.IsZD = false;
            //if (numReserveAmount.Text.Trim().Length > 0) { obj.ReserveAmount = Convert.ToDecimal(numReserveAmount.Text); }
            obj.Contractor = hidContractor.Value;
            obj.DBankCompanyID = hidDBankCompany.Value;
            obj.DBankCompanyName = txtDBankCompany.Text.Trim();
            obj.Remark = txtRemark.Text;
            obj.PaymentCondition = FCKeditor2.Value;
            obj.BankName = txtBankName.Text;
            obj.BankAccount = txtBankAccount.Text;

            //obj.ProjectDOwners = new List<BD_Contract_ProjectDOwner>();
            //string strCompId = Request["chkID"] + "";
            //if (!string.IsNullOrEmpty(strCompId))
            //{
            //    string[] arrCompID = strCompId.Split(',');
            //    BD_Contract_ProjectDOwner item = null;
            //    foreach (string s in arrCompID)
            //    {
            //        item = new BD_Contract_ProjectDOwner();
            //        item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
            //        item.CompanyID = s;
            //        item.ContractID = obj.ID;
            //        obj.ProjectDOwners.Add(item);
            //    }
            //}
        }

	}
}